package com.gulimall.product.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gulimall.common.constant.ProductConstant;
import com.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.gulimall.product.entity.AttrGroupEntity;
import com.gulimall.product.entity.CategoryEntity;
import com.gulimall.product.service.AttrAttrgroupRelationService;
import com.gulimall.product.service.AttrGroupService;
import com.gulimall.product.service.CategoryService;
import com.gulimall.product.vo.AttrRespVo;
import com.gulimall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gulimall.common.utils.PageUtils;
import com.gulimall.common.utils.Query;

import com.gulimall.product.dao.AttrDao;
import com.gulimall.product.entity.AttrEntity;
import com.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationService relationService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrGroupService attrGroupService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存属性信息和其关联的分组信息
     *
     * @param attr attrVo对象
     */
    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        //将提交的vo对象封装为attrEntity
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        //保存属性
        this.save(attrEntity);

        //保存属性的关联关系
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationService.save(relationEntity);
        }


    }

    /**
     * 平台属性-规格参数，属性列表数据查询
     *
     * @param catelogId 分类id
     * @param params    属性基本信息
     * @param attrType  属性类型[0-销售属性，1-基本属性]
     * @return
     */
    @Override
    public PageUtils queryAttrBasePage(Long catelogId, Map<String, Object> params, String attrType) {
        //设置查询条件 select * from pms_attr WHERE (catelog_id = ? AND (attr_id = ? OR attr_name LIKE ?))
        LambdaQueryWrapper<AttrEntity> queryWrapper = Wrappers.lambdaQuery();
        //类型判断attrType = base 查询基本属性，attrType = sale 查询销售属性
        queryWrapper.eq(AttrEntity::getAttrType,
                "base".equals(attrType)
                        ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()
                        : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode()
        );

        if (catelogId != 0) {
            //查询指定catelogId的数据
            queryWrapper.eq(AttrEntity::getCatelogId, catelogId);
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            queryWrapper.and(wrapper -> {
                wrapper.eq(AttrEntity::getAttrId, key).or().like(AttrEntity::getAttrName, key);
            });
        }

        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        List<AttrEntity> records = page.getRecords();

        List<AttrRespVo> collect = records.stream().map(attrEntity -> {
            //封装返回的attr 对象
            AttrRespVo attrRespVo = new AttrRespVo();
            //1. 复制基础属性
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            //2. 设置关联的分类信息
            CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }

            //3. 设置关联的分组信息
            //3.1 获取属性与分组的中间表对象
            LambdaQueryWrapper<AttrAttrgroupRelationEntity> attrWrapper = Wrappers.lambdaQuery();
            attrWrapper.eq(AttrAttrgroupRelationEntity::getAttrId, attrEntity.getAttrId());
            AttrAttrgroupRelationEntity attrRelation = relationService.getOne(attrWrapper);
            if (attrRelation != null) {
                //从中间表中获取属性对应的分组对象
                Long attrGroupId = attrRelation.getAttrGroupId();
                AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrGroupId);
                //设置分组名称
                if (attrGroupEntity != null) {
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            return attrRespVo;
        }).collect(Collectors.toList());

        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(collect);
        return pageUtils;
    }

    /**
     * 根据attrId查询其详细信息，拼接catelogPath（属性完整路径），用于级联选择器数据回显
     *
     * @param attrId 属性id
     * @return attrRespVo对象
     */
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity, attrRespVo);

        //封装分组信息(基本属性才有分组信息)
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //获取中间表对象
            AttrAttrgroupRelationEntity attrRelation =
                    relationService.getOne(Wrappers.lambdaQuery(AttrAttrgroupRelationEntity.class)
                            .eq(attrId != null, AttrAttrgroupRelationEntity::getAttrId, attrId));
            //设置分组信息
            if (attrRelation != null) {
                attrRespVo.setAttrGroupId(attrRelation.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrRelation.getId());
                if (attrGroupEntity != null) {
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }


        //设置分类信息
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.getCatelogPath(catelogId);

        attrRespVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryService.getById(catelogId);
        if (categoryEntity != null) {
            attrRespVo.setCatelogName(categoryEntity.getName());
        }

        return attrRespVo;
    }

    /**
     * 修改属性及其关联信息
     *
     * @param attrVo
     */
    @Transactional
    @Override
    public void updateAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.updateById(attrEntity);

        //修改中间表
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            int count = relationService.count(Wrappers.lambdaQuery(AttrAttrgroupRelationEntity.class)
                    .eq(AttrAttrgroupRelationEntity::getAttrId, attrEntity.getAttrId()));

            if (count == 0) {
                AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
                relationEntity.setAttrId(attrVo.getAttrId());
                relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
                relationService.save(relationEntity);
            } else {
                LambdaUpdateWrapper<AttrAttrgroupRelationEntity> updateWrapper = Wrappers.lambdaUpdate();
                updateWrapper.set(AttrAttrgroupRelationEntity::getAttrGroupId, attrVo.getAttrGroupId());
                updateWrapper.eq(AttrAttrgroupRelationEntity::getAttrId, attrEntity.getAttrId());
                relationService.update(updateWrapper);
            }
        }

    }

    /**
     * 1.根据分组id去分组属性关联表中获取所有属性id的集合
     * 2.根据属性id集合查询到所有关联属性的详细信息
     *
     * @param attrGroupId 分组id
     * @return AttrEntity集合
     */
    @Override
    public List<AttrEntity> getAttrGroupRelationById(Long attrGroupId) {

        LambdaQueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = Wrappers.lambdaQuery();
        if (attrGroupId != null) {
            queryWrapper.eq(AttrAttrgroupRelationEntity::getAttrGroupId, attrGroupId);
        }
        ArrayList<Long> attrIds = new ArrayList<>();
        relationService.list(queryWrapper).forEach(attrRelation -> {
            attrIds.add(attrRelation.getAttrId());
        });

        if (attrIds.size() == 0) {
            return null;
        }

        return this.listByIds(attrIds);
    }

    /**
     * 查询属性分组在所属分类下的所有未关联其他分组的属性
     * 属性分组与属性属于一对多的关系，一个属性只能绑定一个分组，且属性分组与属性的关联范围限制在同一分类下
     *
     * @param attrGroupId 分组id
     * @param params      分页参数
     * @return
     */
    @Override
    public PageUtils getAttrGroupNotRelation(Long attrGroupId, Map<String, Object> params) {
        //1. 获取当前属性分组所属的分类
        AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrGroupId);
        Long catelogId = attrGroupEntity.getCatelogId();

        //2. 获取属性分组所属分类下的所有属性分组(排除当前分组)
        //2.1 查询条件构造器 select * from pms_attr_group where catelog_id = ?
        LambdaQueryWrapper<AttrGroupEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AttrGroupEntity::getCatelogId, catelogId);
        List<AttrGroupEntity> attrGroupList = attrGroupService.list(queryWrapper);
        //2.2 收集所有属性分组的id
        List<Long> groupIds = attrGroupList.stream().map(attrGroup -> {
            return attrGroup.getAttrGroupId();
        }).collect(Collectors.toList());

        //3. 获取到这些分组所关联的所有属性
        List<AttrAttrgroupRelationEntity> relationAttrs = relationService.list(
                Wrappers.lambdaQuery(AttrAttrgroupRelationEntity.class)
                        .in(AttrAttrgroupRelationEntity::getAttrGroupId, groupIds)
        );
        //3.1 收集已关联分组的属性id
        List<Long> attrIds = relationAttrs.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        //4. 从当前分类的所有属性中排除已关联的属性和销售类型的属性
        LambdaQueryWrapper<AttrEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(AttrEntity::getCatelogId, catelogId);
        if (attrIds.size() != 0) {
            wrapper.notIn(AttrEntity::getAttrId, attrIds)
                    .eq(AttrEntity::getAttrType, ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        }
        //4.1 模糊查询
        String key = params.get("key").toString();
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and(w -> {
                w.eq(AttrEntity::getAttrId, key).or().like(AttrEntity::getAttrName, key);
            });
        }
        //5. 返回
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

}